/**
 * 商住房管理
 * @constructor
 */
function BusinessHouse() {

    this.filterType = '1'   // Tab 切换变量
    this.currentPage
    this.rolesArr = []      // 用户权限id数组
    this.houseList          // 缓存 List 数据
    this.dialogData         // 弹窗数据缓存

    var _this = this

    this.init = function() {

        this.initGlobal()
        this.initTab()
        this.initHome()
        this.initDialog()
        this.initDialogSelChange()

        this.getHouseList(this.filterType, 1)
    }

    // 初始化全局变量
    this.initGlobal = function() {

        // 获取权限列表
        var rolesList = JSON.parse(localStorage.getItem('roles'))

        rolesList.forEach(function(role) {
            _this.rolesArr.push(role.roleId)
        })

        if (_this.findRole(_this.rolesArr, [56, 60])) {
            $('#myTabs').append('<button type="button" class="btn btn-info btn-sm pull-right" id="addHouseBtn">新增</button>')
        }
        if (_this.findRole(_this.rolesArr, [56])) {
            $('#myTabs').append('<button type="button" class="btn btn-danger btn-sm pull-right" id="syncHouseBtn">同步</button>')
        }

        // 分页回调
        window.paginationCallback = function (page_index) {
            if(!isPostBack) {
                _this.getHouseList(_this.filterType, page_index+1, 1);
            }
        }

    }

    // 标签初始化
    this.initTab = function() {
        // tab 切换
        $('#myTabs span').not('.active').bind('click', function selHouse(){
            $('.t-apply-box .t-box-title-btn').not('.btnSel').unbind('click')
            $(this).siblings().removeClass('btnSel')
            $(this).addClass('btnSel')
            _this.filterType = $(this).attr("data-type")

            _this.getHouseList(_this.filterType, 1)
            $('.t-apply-box .t-box-title-btn').not('.btnSel').bind('click',selHouse)
        });
    }

    // 主页面事件初始化
    this.initHome = function() {

        // 从丁盯同步数据
        $('body').on('click', '#syncHouseBtn', function() {

            bootbox.confirm({
                message: "确定从丁盯同步数据吗？",
                buttons: {
                    confirm: {
                        label: '确定',
                        className: 'btn-danger'
                    },
                    cancel: {
                        label: '取消',
                        className: 'btn-default'
                    }
                },
                callback: function (result) {
                    if (!result) {
                        return
                    }

                    setTimeout(function() {
                        bootbox.confirm({ message: "正在同步中请稍后！", buttons: { confirm: { label: '确定', className: 'btn-danger' }, cancel: { label: '取消',  className: 'btn-default' } }, callback: function(result) {}})
                    }, 0)

                    PostForm('/cwp/front/sh/apartment!execute', 'uid=R026', 'post', function(result) {

                        if (+result.returnCode) {
                            return tipModal('icon-cross', result.returnMessage)
                        }

                        tipModal('icon-checkmark', result.returnMessage)

                        _this.getHouseList(_this.filterType, 1)
                    })
                }
            })

        })

        // 新增房间
        $('#addHouseBtn').on('click', function () {
            _this.renderDialog(this, 'addHouseTpl')

            // 二级联动初始化
            // 渲染楼栋下拉菜单
            _this.renderAddBuildingSel(function() {
                // 渲染楼层下拉菜单
                _this.renderAddFloorSel($('#dialog .editBuildingId').val())
            })

        })

        // 修改房间 删除房间
        $('#houseTableData').on('click','.editRoom',function(){

            _this.renderDialog(this, 'editHouseTpl')

            // 渲染楼栋下拉菜单
            _this.renderAddBuildingSel(function() {

                $('#dialog .editBuildingId').val(_this.dialogData.buildingId)
                // 渲染楼层下拉菜单
                _this.renderAddFloorSel($('#dialog .editBuildingId').val(), function() {
                    $('#dialog .editFloorNo').val(_this.dialogData.storeyNumber)
                })
            })

            // 设置 select
            $('#dialog .dormitoryType').val(_this.dialogData.roomTypeDictdataId);
        });

        // 开房
        $('#houseTableData').on('click', '.applyRoom', function() {

            _this.renderDialog(this, 'addCustomerTpl')

        })

        // 续住
        $('#houseTableData').on('click', '.editCustomer', function() {

            _this.renderDialog(this, 'editCustomerTpl')
        })

        // 置空
        $('#houseTableData').on('click', '.clearRoom', function() {

            var roomId = $(this).attr('data-roomid')

            bootbox.confirm({
                message: "确定置空吗？",
                buttons: {
                    confirm: {
                        label: '确定',
                        className: 'btn-danger'
                    },
                    cancel: {
                        label: '取消',
                        className: 'btn-default'
                    }
                },
                callback: function (result) {
                    if (!result) {
                        return
                    }

                    // PostForm('/cwp/front/sh/apartment!execute', 'uid=R031&roomId=' + roomId, '', function(result) {
                    //     if (+result.returnCode) {
                    //         return tipModal('icon-cross', result.returnMessage)
                    //     }
                    //
                    //     tipModal('icon-checkMark', result.returnMessage)
                    //
                    //     _this.getHouseList(_this.filterType, _this.currentPage, 1)
                    // })

                    $.getJSON('../../static/json/dormManger/apartment_R031.json',function(result){
                        if (+result.returnCode) {
                            return tipModal('icon-cross', result.returnMessage)
                        }

                        tipModal('icon-checkMark', result.returnMessage)

                        _this.getHouseList(_this.filterType, _this.currentPage, 1)
                    });
                }
            });
        })

    }

    // 初始化弹窗事件
    this.initDialog = function() {

        // 新增商住房
        $('#dialog').on('click', '.addHouse', function() {

            var dialog = $('#dialog')

            var roomNumber = dialog.find('.dormitoryNb').val()
            var roomDesc = dialog.find('.dormitoryDesc').val()
            var roomTypeDictdataId = dialog.find('.dormitoryType').val()
            var buildingId = dialog.find('.editBuildingId').val()        // 楼栋
            var storeyNumber = dialog.find('.editFloorNo').val()    // 楼层

            if(roomNumber != '' && roomTypeDictdataId != '' && buildingId != '' && storeyNumber != ''){

                if (roomNumber.length < 4) {
                    return tipModal('icon-cross', '房间号输入错误')
                }

                var params = "uid=R008&roomNumber="+roomNumber+"&roomDesc="+roomDesc+"&roomTypeDictdataId=" + roomTypeDictdataId + "&buildingId=" + buildingId + "&storeyNumber=" + storeyNumber

                PostForm("/cwp/front/sh/apartment!execute", params, "", function(result){
                    if(result.returnCode == 0){

                        $('#dialog').modal('hide')

                        tipModal("icon-checkmark", result.returnMessage);

                        // 重新获取房间
                        _this.getHouseList(_this.filterType, 1)
                    }else{
                        tipModal("icon-cross", result.returnMessage);
                    }
                }, '');
            }else{
                tipModal("icon-cross", '请输入正确参数');
            }
        })

        // 删除房间
        $('#dialog').on('click', '.delDormitory', function() {

            var roomId = $(this).attr('data-roomId');

            bootbox.confirm({
                message: "确定删除该房间吗？",
                buttons: {
                    confirm: {
                        label: '确定',
                        className: 'btn-danger'
                    },
                    cancel: {
                        label: '取消',
                        className: 'btn-default'
                    }
                },
                callback: function (result) {
                    if (!result) {
                        return
                    }

                    PostForm("/cwp/front/sh/apartment!execute", "uid=R010&roomId=" + roomId, "", function(result){
                        if(result.returnCode == 0){
                            $("#dialog").modal("hide")

                            tipModal("icon-checkmark", result.returnMessage);

                            _this.getHouseList(_this.filterType, 1)
                        }else{
                            tipModal("icon-cross", result.returnMessage);
                        }
                    }, '');
                }
            })
        })

        // 修改房间
        $('#dialog').on('click', '#editDormitoryBtn', function() {

            var dialog = $('#dialog')
            var roomNumber = dialog.find('.dormitoryNb').val()
            var roomId = dialog.find('.dormitoryId').val()
            var roomDesc = dialog.find('.roomDesc').val()
            var buildingId = dialog.find('.editBuildingId').val()
            var storeyNumber = dialog.find('.editFloorNo').val()
            var roomTypeDictdataId = dialog.find('.dormitoryType').val()

            if (!(roomNumber && roomId && buildingId && storeyNumber)) {
                return tipModal('icon-cross', '请输入正确参数')
            }

            if (roomNumber.length < 4) {
                return tipModal('icon-cross', '房间号输入错误')
            }

            PostForm('/cwp/front/sh/apartment!execute', 'uid=R009&roomNumber=' + roomNumber + '&roomId=' + roomId + '&roomDesc=' + roomDesc + '&buildingId=' + buildingId + '&storeyNumber=' + storeyNumber + '&roomTypeDictdataId=' + roomTypeDictdataId, '', function(result) {

                if (+result.returnCode) {
                    return tipModal('icon-cross', result.returnMessage)
                }

                $('#dialog').modal('hide')

                _this.getHouseList(_this.filterType, _this.currentPage, 1)
                tipModal('icon-checkmark', result.returnMessage)
            })
        })

        // 续住
        $('#dialog').on('click', '#confirmDelay', function() {

            var applyRequestId = $('#DelayInput').val()
            var startDate = $('#dialog .form_date_hour_start').text()
            var endDate = $('#dialog .form_date_hour_end').val()

            if (endDate) {
                if (startDate > endDate) {
                    return tipModal('icon-cross', '结束时间不能小于开始时间')
                }

                $("#dialog").modal("hide")
                // PostForm("/cwp/front/sh/apartment!execute", "uid=R030&applyRequestId=" + applyRequestId + "&endDate=" + endDate, "", function(result){
                //     if(result.returnCode == 0){
                //         tipModal("icon-checkmark", result.returnMessage);
                //
                //         // 重新获取房间
                //         _this.getHouseList(_this.filterType, _this.currentPage, 1)
                //     }else{
                //         tipModal("icon-cross", result.returnMessage);
                //     }
                // }, '');

                $.getJSON('../../static/json/dormManger/apartment_R030.json',function(result){
                    if(result.returnCode == 0){
                        tipModal("icon-checkmark", result.returnMessage);

                        // 重新获取房间
                        _this.getHouseList(_this.filterType, _this.currentPage, 1)
                    }else{
                        tipModal("icon-cross", result.returnMessage);
                    }
                });
            } else {
                tipModal("icon-cross", "请选择日期")
            }

        })

        // 开房
        $('#dialog').on('click', '#addCustomer', function() {

            var userName = $('.userName').val()
            var roomId = $('#addInput').val()
            var phoneNo = $('.phoneNo').val()
            var idCard = $('.idCard').val()
            var startDate = $('#dialog .form_date_hour_start').val()
            var endDate = $('#dialog .form_date_hour_end').val()

            if (userName && roomId && phoneNo && idCard && startDate && endDate) {

                // 表单验证
                var validate = new _this.validate()
                if (!validate.isPhone(phoneNo)) {
                    return tipModal('icon-cross', '手机号码输入不正确')
                }
                var idCardRegResult = validate.isCardID(idCard)
                if ( idCardRegResult != 1) {
                    return tipModal('icon-cross', idCardRegResult)
                }
                if (startDate > endDate) {
                    return tipModal('icon-cross', '结束时间不能小于开始时间')
                }

                // PostForm('/cwp/front/sh/apartment!execute', "uid=R027&userName=" + userName + "&roomId=" + roomId + "&phone=" + phoneNo + "&identityCard=" + idCard + "&startDate=" + startDate + "&endDate=" + endDate, "", function(result) {
                //     if(result.returnCode == 0){
                //
                //         $("#dialog").modal("hide")
                //         tipModal("icon-checkmark", result.returnMessage);
                //         // 重新获取房间
                //         _this.getHouseList(_this.filterType, 1)
                //     }else{
                //         tipModal("icon-cross", result.returnMessage);
                //     }
                // })

                $.getJSON('../../static/json/dormManger/apartment_R027.json',function(result){
                    if(result.returnCode == 0){

                        $("#dialog").modal("hide")
                        tipModal("icon-checkmark", result.returnMessage);
                        // 重新获取房间
                        _this.getHouseList(_this.filterType, 1)
                    }else{
                        tipModal("icon-cross", result.returnMessage);
                    }
                });

            } else {
                tipModal("icon-cross", '请输入正确参数');
            }

        })

    }

    // 初始化 Dialog select 事件
    this.initDialogSelChange = function() {

        // 新增 和 修改 二级联动时间绑定
        $('body').on('change', '#dialog .editBuildingId', function() {

            _this.renderAddFloorSel($('#dialog .editBuildingId').val())
        })
    }

    /**
     * 获取房间列表
     * @param filterType 筛选类型 0 -1 1
     * @param pageIndex  页面索引
     * @param notPostBack 非postBack 点击分页按钮时传参
     */
    this.getHouseList = function(filterType, pageIndex, notPostBack) {

        if (!notPostBack) {
            // 重新分页变量
            window.isPostBack = true
        }


        $.getJSON('../../static/json/dormManger/apartment_R019.json',function(data){
            var loaderTable = new LoaderTable('', 'houseTableData', '/cwp/front/sh/apartment!execute', "uid=R019&filter=" + filterType,
                pageIndex || 1, 20, _this.renderHouseList, null)

            _this.currentPage = loaderTable.currentPage
            // loaderTable.Display()
            loaderTable.loadSuccessed(data);
        });
    }

    // 房间列表渲染
    this.renderHouseList = function(result) {

        if(result.returnCode == '0'){
            var outHtml;
            if(result.beans.length == 0){
                outHtml = "<h2 style='text-align: center;'>暂无房间信息</h2>";
            }else{

                _this.houseList = result.beans;

                template.helper('roomTypeDictdataIdType', function(inp) {
                    if(inp == "1009033") {
                        return 'info-box-bg-green';
                    } else if(inp == "1009022"){
                        return 'info-box-bg-yellow';
                    } else {
                        return '';
                    }
                });
                template.helper('roomTypeDictdataIdName', function(inp) {
                    if(inp == "1009033") {
                        return '套房';
                    } else if(inp == "1009022"){
                        return '标间';
                    } else if(inp == "1009011"){
                        return '单间';
                    }
                });
                template.helper('activeStatusHide', function(inp) {
                    if(inp == "1") {
                        return '';
                    } else if (inp == "0"){
                        return 'hide';
                    } else {
                        return "hide";
                    }
                });
                template.helper('activeStatusShow', function(inp) {
                    if(inp == "1") {
                        return '已入住';
                    } else if (inp == "0"){
                        return '未入住';
                    } else {
                        return "已入住";
                    }
                });
                template.helper('activeStatusColor', function(inp) {
                    if(inp == "1") {
                        return 'red';
                    } else if (inp == "0"){
                        return 'green';
                    } else {
                        return "red";
                    }
                });

                result.roles = _this.rolesArr

                template.helper('findRole', _this.findRole)
                outHtml = template('houseListTpl',result);
            }
            $("#houseTableData").html(outHtml);
        }else{
            tipModal("icon-cross", result.returnMessage);
        }
    }

    // 渲染弹窗
    this.renderDialog = function(ele, tplName) {

        var roomId = $(ele).attr('data-roomId');

        var detData;
        if (roomId) {
            var list = _this.houseList;

            for(var i = 0; i< list.length; i++) {
                if (list[i].roomId == roomId) {
                    _this.dialogData = detData = list[i]
                    break
                }
            }
        }

        var htmlTemp = template(tplName, detData)
        $('#dialog .modal-content').html(htmlTemp)

        $("#dialog").modal({
            keyboard: true,
            backdrop: 'static'
        },'show.bs.modal', centerModal());

        // 精确到分
        $(".form_date_hour_start, .form_date_hour_end").not('.readonly').datetimepicker({
            language: 'zh-CN',
            format: "yyyy-mm-dd hh:ii:00",
            autoclose: true,
            minView: "hour",
            maxView: "decade",
            todayBtn: true,
            clearBtn: true
        });
    }

    /***** 新增商住房 *****/
    // 渲染楼栋
    this.renderAddBuildingSel = function(cb) {

        PostForm('/cwp/front/sh/apartment!execute', 'uid=R028', '', function(result) {
            if (+result.returnCode) {
                return tipModal('icon-cross', result.returnMessage)
            }

            var htmlTmp = ''
            result.beans.forEach(function(item) {
                htmlTmp += '<option value="' + item.buildingId + '">' + item.buildingName + '</option>'
            })

            $('#dialog .editBuildingId').html(htmlTmp)

            cb()
        })
    }
    // 渲染楼层
    this.renderAddFloorSel = function(buildingId, cb) {
        PostForm('/cwp/front/sh/apartment!execute', 'uid=R029&buildingId=' + buildingId, '', function(result) {
            if (+result.returnCode) {
                return tipModal('icon-cross', result.returnMessage)
            }

            var htmlTmp = ''
            result.beans.forEach(function (item) {
                htmlTmp += '<option value="' + item.storeyNumber + '">' + item.storeyNumber + '</option>'
            })

            $('#dialog .editFloorNo').html(htmlTmp)

            if (cb) {
                cb()
            }
        })
    }
    /***** /新增商住房 *****/

    // 查找权限
    this.findRole = function(roles, item) {

        var flag = false
        for (var i = 0, l = item.length; i < l; i++) {
            if (roles.indexOf(item[i]) != -1) {
                flag = true
                break;
            }
        }

        return flag
    }

    // 表单验证
    this.validate = function() {

        // 手机号验证
        this.isPhone = function(pNo) {
            return (/^[1][3,4,5,6,7,8,9][0-9]{9}$/).test(pNo)
        }

        // 身份证号验证
        this.aCity={11:"北京",12:"天津",13:"河北",14:"山西",15:"内蒙古",21:"辽宁",22:"吉林",23:"黑龙江",31:"上海",32:"江苏",33:"浙江",34:"安徽",35:"福建",36:"江西",37:"山东",41:"河南",42:"湖北",43:"湖南",44:"广东",45:"广西",46:"海南",50:"重庆",51:"四川",52:"贵州",53:"云南",54:"西藏",61:"陕西",62:"甘肃",63:"青海",64:"宁夏",65:"新疆",71:"台湾",81:"香港",82:"澳门",91:"国外"}

        this.isCardID = function (sId) {
            var iSum = 0;

            if (!/^\d{17}(\d|x)$/i.test(sId)) {
                return "你输入的身份证长度或格式错误";
            }
            sId = sId.replace(/x$/i, "a");
            if (this.aCity[parseInt(sId.substr(0, 2))] == null) {
                return "你的身份证地区非法";
            }
            var sBirthday = sId.substr(6, 4) + "-" + Number(sId.substr(10, 2)) + "-" + Number(sId.substr(12, 2));
            var d = new Date(sBirthday.replace(/-/g, "/"));
            if (sBirthday != (d.getFullYear() + "-" + (d.getMonth() + 1) + "-" + d.getDate())) {
                return "身份证上的出生日期非法";
            }
            for (var i = 17; i >= 0; i--){
                iSum += (Math.pow(2, i) % 11) * parseInt(sId.charAt(17 - i), 11);
            }
            if (iSum % 11 != 1){
                return "你输入的身份证号非法";
            }
            return true;
        }
    }

}

$(function() {

    new BusinessHouse().init()

})